package com.elitel.frame.main.security;

import com.elitel.frame.base.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * TODO: CustomAuthenticationProvider
 *
 * @since 2020-02-26
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

  @Autowired private UserInfoService customUserService;

  @Autowired private BCryptPasswordEncoder passwordEncoder;

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    UserDetails userDetails = customUserService.loadUserByUsername(username);

    if (userDetails == null) {
      throw new UsernameNotFoundException("");
    }

    if (!passwordEncoder.matches(password, userDetails.getPassword())) {
      throw new DisabledException("");
    }

    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
            username, userDetails.getPassword(), userDetails.getAuthorities());
    return usernamePasswordAuthenticationToken ;
  }

  @Override
  public boolean supports(Class<?> aClass) {
    return true;
  }
}
